<template>
  <div class="auth-container" :class="{ 'mobile': appStore.isMobile }">
    <el-card class="auth-card">
      <!-- 页面头部 -->
      <template #header>
        <div class="auth-header" :class="{ 'mobile-header': appStore.isMobile }">
          <h2 class="auth-title">
            <el-icon>
              <Key />
            </el-icon>
            企业微信应用授权
          </h2>
        </div>
      </template>

      <div v-loading="pageLoading" class="auth-content">
        <!-- 授权成功状态 -->
        <div v-if="authStatus?.is_authorized && authDetail" class="auth-success">
          <div class="success-icon">
            <el-icon color="#67C23A" size="48">
              <SuccessFilled />
            </el-icon>
          </div>
          <h3 class="success-title">已绑定{{ authDetail.corp_name }}</h3>
          <p class="success-desc">您的企业微信应用已成功授权，可以正常使用相关功能</p>

          授权详情
          <div class="auth-details">
            <!-- 企业信息 -->
            <div class="detail-section" v-if="authDetail.kefu_type === 1">
              <h4>企业信息</h4>
              <div class="detail-grid" :class="{ 'mobile-grid': appStore.isMobile }">
                <div class="detail-item">
                  <div class="detail-avatar">
                    <img v-if="authDetail.auth_corp_info.corp_round_logo_url"
                      :src="authDetail.auth_corp_info.corp_round_logo_url" alt="企业logo" />
                    <el-icon v-else>
                      <User />
                    </el-icon>
                  </div>
                  <div class="detail-info">
                    <div class="detail-label">企业名称</div>
                    <div class="detail-value">{{ authDetail.corp_name || '未知' }}</div>
                    <div class="detail-sub">ID: {{ authDetail.corpid || '未知' }}</div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 管理员信息 -->
            <!-- <div class="detail-section">
              <h4>管理员信息</h4>
              <div class="admin-info" :class="{ 'mobile-admin': appStore.isMobile }">
                <div class="admin-avatar">
                  <img 
                    v-if="authDetail.auth_corp_info.auth_info.avatar" 
                    :src="authDetail.auth_corp_info.auth_info.avatar" 
                    alt="管理员头像"
                  />
                  <el-icon v-else><User /></el-icon>
                </div>
                <div class="admin-details">
                  <div class="admin-name">{{ authDetail.auth_corp_info.auth_corp_info.auth_info.name || '未知管理员' }}</div>
                  <div class="admin-id">用户ID: {{ authDetail.auth_corp_info.auth_corp_info.auth_info.userid || '未知' }}</div>
                </div>
              </div>
            </div> -->

            <!-- 授权信息 -->
            <div class="detail-section" v-if="authDetail.kefu_type === 1">
              <h4>授权信息</h4>
              <div class="auth-info">
                <div class="info-row" :class="{ 'mobile-row': appStore.isMobile }">
                  <span class="info-label">授权时间：</span>
                  <span class="info-value">{{ authDetail.created_at }}</span>
                </div>
                <div class="info-row" :class="{ 'mobile-row': appStore.isMobile }">
                  <span class="info-label">过期时间：</span>
                  <span class="info-value">{{ authDetail.auth_corp_info?.verified_end_time }}</span>
                </div>
                <div class="info-row" :class="{ 'mobile-row': appStore.isMobile }">
                  <el-button type="danger" @click="handleRemove">解除</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 未授权状态 -->
        <div v-else-if="!pageLoading" class="auth-pending">
          <div class="pending-icon">
            <el-icon color="#E6A23C" size="48">
              <Warning />
            </el-icon>
          </div>
          <h3 class="pending-title">应用未授权</h3>


          <div class="qr-section" :class="{ 'mobile-qr': appStore.isMobile }">
            <div v-if="qrCodeUrl" class="qr-container">
              <div class="qr-code">
                <el-image :src="qrCodeUrl" alt="授权二维码" @error="handleQRError" :preview-src-list="[qrCodeUrl]"
                  fit="contain" class="qr-image" />
              </div>
              <div class="qr-footer">
                <p class="qr-tip">请使用企业微信扫描上方二维码完成授权</p>
                <p class="qr-click-tip">（点击二维码可放大查看）</p>
              </div>
            </div>
            <div v-else class="qr-loading">
              <el-icon class="is-loading">
                <Loading />
              </el-icon>
              <p>正在获取授权二维码...</p>
            </div>
          </div>

          <div class="auth-notice" :class="{ 'mobile-notice': appStore.isMobile }">
            <el-alert title="授权须知" type="info" :closable="false" show-icon>
              <template #default>
                <ul class="notice-list">
                  <li>只有企业微信的管理员才能完成应用授权</li>
                  <li>授权后可以使用客服功能</li>
                  <li>授权完成后页面会自动刷新显示授权信息</li>
                </ul>
              </template>
            </el-alert>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Key, SuccessFilled, Warning, Loading, Refresh, User
} from '@element-plus/icons-vue'
import {
  getAuthStatus,
  getAuthDetail,
  getAuthQRCode,
  refreshAuthQRCode,
  cancelAuth,
  checkAuthStatus,
  type AuthStatus,
  type AuthDetail,
  removeAuth
} from '@/api/auth'
import useAppStore from '@/stores/modules/app'

// 响应式数据
const pageLoading = ref(true)
const qrLoading = ref(false)
const cancelLoading = ref(false)
const authStatus = ref<AuthStatus | null>(null)
const authDetail = ref<AuthDetail | null>(null)
const qrCodeUrl = ref('')
const pollingTimer = ref<number | null>(null)
const appStore = useAppStore()

// 权限范围标签映射
const scopeLabels: Record<string, string> = {
  'snsapi_base': '基础信息',
  'snsapi_userinfo': '用户信息',
  'snsapi_contact': '通讯录',
  'snsapi_message': '消息推送',
  'snsapi_calendar': '日程管理',
  'snsapi_checkin': '打卡数据',
  'snsapi_approval': '审批数据'
}

// 获取权限范围标签
const getScopeLabel = (scope: string): string => {
  return scopeLabels[scope] || scope
}

// 格式化时间
const formatTime = (time: string): string => {
  return new Date(time).toLocaleString('zh-CN')
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

// 处理二维码加载错误
const handleQRError = () => {
  ElMessage.error('二维码加载失败，请刷新重试')
}


// 获取授权状态
const fetchAuthStatus = async () => {
  try {
    const response = await getAuthStatus()
    console.log('resoonse', response);
    if (response.code === 1) {
      authStatus.value = response
      authDetail.value = response
      console.log(authStatus.value);

      return response.is_authorized
    } else {
      throw new Error(response.msg || '获取授权状态失败')
    }
  } catch (error) {
    console.error('获取授权状态失败:', error)
    ElMessage.error('获取授权状态失败')
    return false
  }
}

// 获取授权详情
const fetchAuthDetail = async () => {
  try {
    const response = await getAuthDetail()
    if (response.code === 1) {
      authDetail.value = response.data
    } else {
      throw new Error(response.message || '获取授权详情失败')
    }
  } catch (error) {
    console.error('获取授权详情失败:', error)
    ElMessage.error('获取授权详情失败')
  }
}

//解除授权
const handleRemove = async () => {
  try {
    await ElMessageBox.confirm('确定要解除授权吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    const response = await removeAuth()
    if (response.code === 1) {
      ElMessage.success('解除授权成功')
      await initPage()
      window.location.reload()
    } else {
      throw new Error(response.message || '解除授权失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('解除授权失败:', error)
      ElMessage.error('解除授权失败')
    }
  }
}

// 获取授权二维码
const fetchQRCode = async () => {
  try {
    qrLoading.value = true
    const response = await getAuthQRCode()
    if (response.code === 1) {
      qrCodeUrl.value = response.qrcode
    } else {
      throw new Error(response.message || '获取二维码失败')
    }
  } catch (error) {
    console.error('获取二维码失败:', error)
    ElMessage.error('获取二维码失败')
  } finally {
    qrLoading.value = false
  }
}

// 开始轮询检查授权状态
const startPolling = () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
  }

  pollingTimer.value = window.setInterval(async () => {
    try {
      const response = await checkAuthStatus()
      if (response.code === 1 && response.is_authorized) {
        // 授权成功，停止轮询并重新加载页面数据
        stopPolling()
        ElMessage.success('授权成功！')
        await initPage()
      }
    } catch (error) {
      console.error('检查授权状态失败:', error)
    }
  }, 3000) // 每3秒检查一次
}

// 停止轮询
const stopPolling = () => {
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }
}

// 初始化页面
const initPage = async () => {
  try {
    pageLoading.value = true

    // 获取授权状态
    const isAuthorized = await fetchAuthStatus()

    console.log('isAuthorized', isAuthorized);

    if (isAuthorized) {
      // 已授权，获取详情
      // await fetchAuthDetail()
      stopPolling()
    } else {
      // 未授权，获取二维码并开始轮询
      await fetchQRCode()
      startPolling()
    }
  } catch (error) {
    console.error('初始化页面失败:', error)
  } finally {
    pageLoading.value = false

  }
}

// 页面挂载
onMounted(() => {
  initPage()
})

// 页面卸载
onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
.auth-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.auth-card {
  max-width: 800px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.auth-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.auth-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.auth-content {
  min-height: 400px;
  padding: 20px 0;
}

/* 授权成功样式 */
.auth-success {
  text-align: center;
}

.success-icon {
  margin-bottom: 16px;
}

.success-title {
  font-size: 24px;
  font-weight: 600;
  color: #67C23A;
  margin: 0 0 8px 0;
}

.success-desc {
  color: #606266;
  margin: 0 0 32px 0;
  font-size: 14px;
}

.auth-details {
  text-align: left;
  margin-top: 32px;
}

.detail-section {
  margin-bottom: 32px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 6px;
}

.detail-avatar {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  overflow: hidden;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.detail-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.detail-info {
  flex: 1;
}

.detail-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.detail-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.detail-sub {
  font-size: 12px;
  color: #606266;
  margin-top: 2px;
}

.admin-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: white;
  border-radius: 8px;
}

.admin-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.admin-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.admin-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.admin-id {
  font-size: 12px;
  color: #909399;
}

.auth-info {
  background: white;
  padding: 16px;
  border-radius: 8px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  font-size: 14px;
  color: #606266;
  width: 80px;
  flex-shrink: 0;
}

.info-value {
  font-size: 14px;
  color: #303133;
}

.scope-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 未授权样式 */
.auth-pending {
  text-align: center;
}

.pending-icon {
  margin-bottom: 16px;
}

.pending-title {
  font-size: 24px;
  font-weight: 600;
  color: #E6A23C;
  margin: 0 0 8px 0;
}

.pending-desc {
  color: #606266;
  margin: 0 0 32px 0;
  font-size: 14px;
}

.qr-section {
  margin-bottom: 32px;
}

.qr-container {
  display: inline-block;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qr-code {
  width: 280px;
  height: 280px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafafa;
  margin: 0 auto 16px auto;
}

.qr-code img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 6px;
}

.qr-image {
  width: 100%;
  height: 100%;
  border-radius: 6px;
  cursor: pointer;
}

.qr-image :deep(.el-image__inner) {
  border-radius: 6px;
  transition: transform 0.3s ease;
}

.qr-image:hover :deep(.el-image__inner) {
  transform: scale(1.05);
}

.qr-footer {
  text-align: center;
}

.qr-tip {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

.qr-click-tip {
  margin: 4px 0 0 0;
  font-size: 12px;
  color: #909399;
  font-style: italic;
}

.qr-loading {
  padding: 25px 10px;
  color: #909399;
  text-align: center;
}

.qr-loading .el-icon {
  font-size: 24px;
  margin-bottom: 12px;
}

.qr-loading p {
  margin: 0;
  font-size: 12px;
}

.auth-notice {
  max-width: 500px;
  margin: 0 auto;
  text-align: left;
}

.notice-list {
  margin: 0;
  padding-left: 20px;
}

.notice-list li {
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .auth-container {
    padding: 10px;
    min-height: auto;
  }

  .auth-container.mobile {
    padding: 8px;
  }

  .auth-card {
    margin: 0;
    border-radius: 12px;
  }

  .auth-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
    text-align: center;
  }

  .auth-header.mobile-header {
    padding: 15px 10px;
  }

  .auth-title {
    font-size: 16px;
    justify-content: center;
  }

  .auth-content {
    padding: 15px 0;
    min-height: auto;
  }

  .success-title,
  .pending-title {
    font-size: 20px;
  }

  .success-desc,
  .pending-desc {
    font-size: 13px;
    margin: 0 0 24px 0;
  }

  .detail-section {
    margin-bottom: 24px;
    padding: 15px;
  }

  .detail-section h4 {
    font-size: 15px;
    margin-bottom: 12px;
  }

  .detail-grid {
    grid-template-columns: 1fr;
  }

  .detail-grid.mobile-grid {
    display: block;
  }

  .detail-item {
    flex-direction: row;
    align-items: center;
    text-align: left;
    padding: 12px;
    margin-bottom: 8px;
  }

  .detail-avatar {
    width: 40px;
    height: 40px;
    margin-right: 12px;
    margin-bottom: 0;
  }

  .detail-info {
    flex: 1;
  }

  .detail-value {
    font-size: 13px;
  }

  .detail-label {
    font-size: 11px;
  }

  .detail-sub {
    font-size: 11px;
  }

  .admin-info {
    flex-direction: row;
    text-align: left;
    padding: 12px;
  }

  .admin-info.mobile-admin {
    align-items: center;
  }

  .admin-avatar {
    width: 36px;
    height: 36px;
    margin-right: 12px;
    margin-bottom: 0;
  }

  .admin-name {
    font-size: 14px;
    margin-bottom: 2px;
  }

  .admin-id {
    font-size: 11px;
  }

  .auth-info {
    padding: 12px;
  }

  .info-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
    margin-bottom: 10px;
  }

  .info-row.mobile-row {
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 8px;
  }

  .info-label {
    width: auto;
    font-size: 12px;
    font-weight: 500;
  }

  .info-value {
    font-size: 13px;
  }

  .qr-section.mobile-qr {
    margin-bottom: 24px;
  }

  .qr-container {
    padding: 15px;
    border-radius: 8px;
  }

  .qr-code {
    width: 160px;
    height: 160px;
    margin: 0 auto 12px auto;
  }

  .qr-footer {
    text-align: center;
  }

  .qr-footer .qr-tip {
    font-size: 13px;
    margin-bottom: 10px;
  }

  .qr-footer .qr-click-tip {
    font-size: 12px;
    margin-bottom: 10px;
  }

  .qr-footer .el-button {
    font-size: 13px;
    padding: 6px 12px;
    min-height: 32px;
  }

  .qr-loading {
    padding: 30px 15px;
  }

  .qr-loading .el-icon {
    font-size: 28px;
    margin-bottom: 10px;
  }

  .qr-loading p {
    font-size: 13px;
  }

  .auth-notice {
    max-width: none;
    margin: 0;
  }

  .auth-notice.mobile-notice .el-alert {
    border-radius: 8px;
  }

  .notice-list {
    padding-left: 16px;
  }

  .notice-list li {
    font-size: 13px;
    margin-bottom: 6px;
    line-height: 1.4;
  }
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
  .auth-container {
    padding: 5px;
  }

  .auth-title {
    font-size: 15px;
    gap: 6px;
  }

  .auth-content {
    padding: 10px 0;
  }

  .success-title,
  .pending-title {
    font-size: 18px;
  }

  .detail-section {
    padding: 12px;
    margin-bottom: 16px;
  }

  .detail-section h4 {
    font-size: 14px;
  }

  .detail-item {
    padding: 10px;
  }

  .detail-avatar {
    width: 36px;
    height: 36px;
  }

  .admin-avatar {
    width: 32px;
    height: 32px;
  }

  .qr-code {
    width: 140px;
    height: 140px;
  }

  .qr-footer .el-button {
    font-size: 12px;
    padding: 5px 10px;
    min-height: 30px;
  }

  .qr-footer .qr-tip {
    font-size: 12px;
  }

  .qr-footer .qr-click-tip {
    font-size: 12px;
  }

  .qr-loading {
    padding: 25px 10px;
  }

  .qr-loading .el-icon {
    font-size: 24px;
  }

  .qr-loading p {
    font-size: 12px;
  }
}

/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
  .qr-footer a {
    min-height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 120px;
  }

  .detail-item {
    min-height: 60px;
  }

  .admin-info {
    min-height: 60px;
  }
}

/* 加载动画 */
.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>